from tkinter import ttk
import tkinter
import os


def create_treeview(dict1, window):
    # leftFrame = tkinter.Frame(window)
    # leftFrame.pack(side=tkinter.LEFT, fill=tkinter.Y)
    tree = ttk.Treeview(window)

    # ========================================================================
    # 生成树列表
    var = ''
    for key in dict1:  # 寻找树的主干
        if var.__len__() < key.__len__():
            var = key
    parent_path = var
    list1 = []
    while (parent_path.__len__() > 4):
        list1.append(parent_path)
        parent_path = os.path.dirname(parent_path)
    list1.reverse()
    # 先完成最深的一个目录的目录结构（完成树的主干）
    i1 = -1
    for k in list1:
        if i1 == -1:
            tree.insert("", 0, k, text=k, values=(k))
        else:
            tree.insert(list1[i1], 0, k, text=k[k.rfind('\\') + 1:] + '(dir)', values=(k))
        i1 += 1
    # 吧其他的目录结构也添加到树上（完成树的支干）
    for key in dict1:
        if key not in list1:
            tree.insert(os.path.dirname(key), 0, key, text=key[key.rfind('\\') + 1:] + '(dir)', values=(key))
    # 把所有文件添加到树上（完成枝叶）
    for key in dict1:
        v = dict1[key]
        for v1 in v:
            v1 = v1.replace(' ', '#')
            tree.insert(key, 0, v1, text=v1[v1.rfind('\\') + 1:], values=(v1))
    # ============================================================================
    tree.yview()
    tree.xview()
    return tree
